package apisvr

import (
	"context"
	"fmt"

	"gitee.com/mkwchecking/sr-admin/cmd"
	"gitee.com/mkwchecking/sr-admin/cmd/args"

	"github.com/spf13/cobra"
)

var ServerCmd = &cobra.Command{
	Use:   "server",
	Short: "Start Api Server",
	RunE:  parseArgs,
}

var ServerArg = struct {
	Config *args.ConfigArgs
}{
	Config: &args.ConfigArgs{},
}

func init() {
	cmd.RootCmd().AddCommand(ServerCmd)
	ServerArg.Config.Parse(ServerCmd)
}

func parseArgs(cmd *cobra.Command, args []string) error {

	return startUp(cmd.Context(), ServerArg.Config)
}

func startUp(ctx context.Context, args *args.ConfigArgs) error {
	fmt.Printf("Will start web server with cfgs: %+v \n", args)

	app, err := newApiSvrApp(ctx, args)
	if err != nil {
		return err
	}

	httpSvr, err := getInternalHttpServer()
	if err != nil {
		return err
	}
	app.AddServer(httpSvr)

	// install and start
	if err := app.Install(app.Context(), false); err != nil {
		return err
	}

	if err := app.Start(context.Background()); err != nil {
		return err
	}

	return nil
}
